/**
 * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package cn.bluemobi.dylan.step.activity.skeleton;


import static cn.bluemobi.dylan.step.activity.skeleton.TemplateActivity.getSelectedIndex;

import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.huawei.hms.mlsdk.skeleton.MLSkeletonAnalyzerSetting;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.bluemobi.dylan.step.R;
import cn.bluemobi.dylan.step.activity.adapter.skeleton.GridItem;
import cn.bluemobi.dylan.step.camera.CameraConfiguration;
import cn.bluemobi.dylan.step.camera.CameraSelector;
import cn.bluemobi.dylan.step.camera.LensEngine;
import cn.bluemobi.dylan.step.camera.LensEnginePreview;
import cn.bluemobi.dylan.step.step.bean.TiaoShengData;
import cn.bluemobi.dylan.step.step.utils.DbUtils;
import cn.bluemobi.dylan.step.transactor.LocalSketlonTranstor;
import cn.bluemobi.dylan.step.views.overlay.GraphicOverlay;


public final class HumanSkeletonActivity extends AppCompatActivity
        implements ActivityCompat.OnRequestPermissionsResultCallback, CompoundButton.OnCheckedChangeListener, View.OnClickListener {
    private static final String TAG = "HumanSkeletonActivity";

    public static final int UPDATE_VIEW = 102;

    public static final String SIMILARITY = "similarity";

    private static boolean isSimilarityChecked = false;

    private static boolean isYogaChecked = false;

    private GraphicOverlay graphicOverlay;

    private Button templateSelect;

    private ImageView templateImgView;

    private TextView templateSimilarityTextView;

    private RelativeLayout templateSimilarityImageLayout;

    private LensEngine lensEngine = null;

    private LensEnginePreview preview;

    private CameraConfiguration cameraConfiguration = null;

    private int facing = CameraConfiguration.CAMERA_FACING_BACK;

    private Camera mCamera;

    private LocalSketlonTranstor localSketlonTranstor;

    private Handler mHandler = new MsgHandler(this);

    private static boolean isAsynchronous = true;



    public static TextView textView_step;
    public static Button button_start;
    public static Button button_start1;
    public static int num = 0;
    public static boolean processState=false;
    private static int processState1 = 0;
    private static int tt = 0;
    public static String b;
    public static String b1;
    private static String CURRENT_DATE = "";//时间




    private static class MsgHandler extends Handler {
        WeakReference<HumanSkeletonActivity> mMainActivityWeakReference;

        MsgHandler(HumanSkeletonActivity mainActivity) {
            mMainActivityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HumanSkeletonActivity mainActivity = mMainActivityWeakReference.get();
            if (mainActivity == null) {
                return;
            }

            Log.i(TAG, "msg what :" + msg.what);
            if (msg.what == UPDATE_VIEW) {
                Bundle bundle = msg.getData();
                float result = bundle.getFloat(SIMILARITY);
                mainActivity.templateSimilarityTextView.setText("similarity:" + (int) (result * 100) + "%  ");
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_human_skeleton);
        setIsAsynchronous(false);
        preview = findViewById(R.id.firePreview);
        templateSimilarityTextView = findViewById(R.id.tv_similarity);
        templateImgView = findViewById(R.id.template_image_view);
        templateSimilarityImageLayout = findViewById(R.id.similarity_layout);

        findViewById(R.id.back).setOnClickListener(this);
        graphicOverlay = findViewById(R.id.fireOverlay);

        this.cameraConfiguration = new CameraConfiguration();
        this.cameraConfiguration.setCameraFacing(CameraConfiguration.CAMERA_FACING_FRONT);
        createLensEngineAndAnalyzer(isYogaChecked);

        textView_step=(TextView) findViewById(R.id.tv_step);
        button_start=(Button) findViewById(R.id.btn_start);
        button_start1=(Button) findViewById(R.id.btn_start1);
        textView_step.setText(num + "");
        button_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView_step.setText("0");
                if (processState==true || processState1 > 0){
                    button_start.setText("开始");
                    button_start1.setText("暂停");
                    b = "开始";
                    b1 = "暂停";
                    processState1 = 0;
                    tt=0;
                    processState=false;
                    save();
                    Toast.makeText(HumanSkeletonActivity.this, "您跳了"+num+"圈！\n记录已保存！", Toast.LENGTH_SHORT).show();

                }else{
                    button_start.setText("结束");
                    b = "结束";
                    b1 = "暂停";
                    processState=true;
                }
                num=0;
            }
        });
        button_start1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (processState==true){
                    button_start1.setText("继续");
                    b1 = "继续";
                    processState1++;
                    tt++;
                    processState=false;
                }else if(processState==false&&tt>0){
                    button_start1.setText("暂停");
                    b1 = "暂停";
                    tt=0;
                    processState=true;
                }
            }
        });

    }

    /**
     * 获取当天日期
     *
     * @return
     */
    private String getTodayDate() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public void save(){
        CURRENT_DATE = getTodayDate();
        TiaoShengData tiaoShengData = new TiaoShengData();
        tiaoShengData.setTime(CURRENT_DATE);
        tiaoShengData.setNumber(num);
        DbUtils.insert(tiaoShengData);
    }



    private void createLensEngineAndAnalyzer(boolean isYogaChecked) {
        if (this.lensEngine == null) {
            this.lensEngine = new LensEngine(this, this.cameraConfiguration, this.graphicOverlay);
        }
        MLSkeletonAnalyzerSetting setting;
        if (isYogaChecked) {
            setting = new MLSkeletonAnalyzerSetting.Factory()
                    .setAnalyzerType(MLSkeletonAnalyzerSetting.TYPE_YOGA)
                    .create();
            Log.i(TAG, "yogamode");
        } else {
            setting = new MLSkeletonAnalyzerSetting.Factory().create();
            Log.i(TAG, "skeletonmode");
        }

        this.localSketlonTranstor = new LocalSketlonTranstor(setting, this, mHandler);
        this.lensEngine.setMachineLearningFrameTransactor(localSketlonTranstor);
    }

    private void startLensEngine() {
        if (this.lensEngine != null) {
            try {
                this.preview.start(this.lensEngine, true);
            } catch (IOException e) {
                Log.e(TAG, "Unable to start lensEngine." + e.getMessage());
                this.lensEngine.release();
                this.lensEngine = null;
            }
        }
    }


    public static void setIsAsynchronous(boolean isAsynchronous) {
        HumanSkeletonActivity.isAsynchronous = isAsynchronous;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.back) {
            finish();
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.i(TAG, "Set facing");
        if (this.lensEngine != null) {
            if (isChecked) {
                this.facing = CameraConfiguration.CAMERA_FACING_FRONT;
                this.cameraConfiguration.setCameraFacing(this.facing);
            } else {
                this.facing = CameraConfiguration.CAMERA_FACING_BACK;
                this.cameraConfiguration.setCameraFacing(this.facing);
            }
        }

        this.preview.stop();
        reStartLensEngine();
    }

    private void reStartLensEngine() {
        startLensEngine();
        if (null != this.lensEngine) {
            this.mCamera = this.lensEngine.getCamera();
            try {
                this.mCamera.setPreviewTexture(this.preview.getSurfaceTexture());
            } catch (IOException e) {
                Log.i(TAG, "initViews IOException, " + e.getMessage());
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        preview.stop();
        createLensEngineAndAnalyzer(isYogaChecked);
        startLensEngine();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        try {
            startLensEngine();
        }catch (Exception e){
            Toast.makeText(HumanSkeletonActivity.this, "请打开相机权限", Toast.LENGTH_SHORT).show();
            finish();
        }
        if (getSelectedIndex() != -1) {
            GridItem mlSkeleton =
                    TemplateActivity.getTemplateDataMap().get(TemplateActivity.getKey() + getSelectedIndex());
            if (mlSkeleton != null) {
                templateImgView.setImageBitmap(mlSkeleton.getBitmap());
            }
        } else {
            GridItem skeleton = TemplateActivity.getTemplateDataMap().get("key0");
            if (skeleton != null) {
                templateImgView.setImageBitmap(skeleton.getBitmap());
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        preview.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (lensEngine == null) {
            lensEngine.release();
        }

        isSimilarityChecked = false;
        setIsAsynchronous(false);
    }

    public static boolean isOpenStatus() {
        return isSimilarityChecked;
    }

    public static boolean isYogaChecked() {
        return isYogaChecked;
    }
}
